import Taro from "@tarojs/taro";
import Interceptor from './util/Interceptor';
import { deepClone, mergeConfig } from './util/index';
class Axios{
  constructor(config) {
    // 默认配置
    this.defaults = deepClone(config);
    //拦截器
    this.interceptors = {
      request : new Interceptor(),
      response : new Interceptor()
    }
  }
  get (url,config={}) {
    config.method = 'GET';
    config.url = url;
    return this.request(config);
  }
  post (url, data = {}, config={}){
    config.method = 'POST';
    config.url = url;
    config.data = data;
    return this.request(config);
  }
  create (config) {
    return new Axios(config);
  }
  //request请求
  request (config) {
    //配置合并
    let configs = mergeConfig(this.defaults, config);
    //将配置转成 Promise 对象，链式调用和返回 Promise 对象
    let promise = Promise.resolve(configs);
    
    // 处理拦截器链
    promise = this.processInterceptors(promise, 'request');
    promise = promise.then(this.send);
    promise = this.processInterceptors(promise, 'response');
    
    //返回响应信息
    return promise;
  }
  send (configs) {
    return new Promise((resolve, reject) => {
      try {
        Taro.request({
          url: configs.baseURL + configs.url,
          header: {
            ...configs.headers
          },
          timeout: configs.timeout,
          method: configs.method,
          data: configs.data,
          success: (res) => {
            if (res.statusCode >= 200 && res.statusCode < 300) {
              resolve(res);
            } else {
              reject(res);
            }
          },
          fail: reject
        })
      } catch (error) {
        reject(error);
      }
    })
  }

  // 处理拦截器链
  processInterceptors(promise, type) {
    const handlers = this.interceptors[type].handlers;
    handlers.forEach(handler => {
      promise = promise.then(handler.resolvedHandler, handler.rejectedHandler);
    });
    return promise;
  }
}
export default Axios;